package com.eastfair.certificate.service.impl;

import com.eastfair.boot.service.SuperCacheServiceImpl;
import com.eastfair.cache.dynamicfrom.FormFieldGroupCacheKeyBuilder;
import com.eastfair.certificate.dao.FormFieldGroupMapper;
import com.eastfair.certificate.entity.FormField;
import com.eastfair.certificate.entity.FormFieldGroup;
import com.eastfair.certificate.entity.FormFieldSubsystem;
import com.eastfair.certificate.enumeration.FormFieldSubsystemFieldTypeAttributeEnum;
import com.eastfair.certificate.enumeration.FormFieldSubsystemMethodTypeEnum;
import com.eastfair.certificate.service.FormFieldGroupService;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.certificate.service.FormFieldService;
import com.eastfair.certificate.service.FormFieldSubsystemService;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.model.CacheKeyBuilder;
import com.eastfair.database.mybatis.conditions.Wraps;
import com.eastfair.database.mybatis.conditions.query.QueryWrap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;

import java.util.Collection;

//import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.aop.framework.AopContext;
import com.eastfair.annotation.annotation.cache.Magic;
import com.eastfair.annotation.annotation.cache.Cache;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
//import com.baomidou.dynamic.datasource.annotation.DS;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

import com.eastfair.certificate.vo.*;
import com.eastfair.certificate.dto.*;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * <p>
 * 业务实现类
 * 动态表单组
 * </p>
 *
 * @author ligang
 * @date 2023-05-17
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class FormFieldGroupServiceImpl extends SuperCacheServiceImpl<FormFieldGroupMapper, FormFieldGroup> implements FormFieldGroupService {
    @Autowired
    FormFieldService formFieldService;

    @Autowired
    FormFieldSubsystemService formFieldSubsystemService;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<FormFieldGroup> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }

    /**
     * 处理新增相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerSave(FormFieldGroup model) {
        //雪花ID,不需要分库分表
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        model.setIsDeleted(BusinessConstant.NO);
        model.setIsEnabled(BusinessConstant.YES);
        return R.successDef();
    }

    /**
     * 处理修改之后的相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerUpdateByIdBack(FormFieldGroup model) {
        //修改子集
        formFieldService.initFormField(model);
        return R.successDef();
    }

    @Override
    public R<Boolean> handlerSaveBack(FormFieldGroup model) {
        //添加子集
        formFieldService.initFormField(model);
        return R.successDef();
    }

    /**
     * 通用查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    public List<FormFieldGroup> list(FormFieldGroupDTO modelDTO, List<Long> ids) {
        return ((FormFieldGroupService) AopContext.currentProxy()).listOfCache(modelDTO, ids);
    }


    /**
     * 缓存查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    @Cache(key = "",
            magic = @Magic(
                    key = "{" +
                            "{'name', #args[0]?.name}," +
                            "{'languageType', #args[0]?.languageType}," +
                            "{'className', #args[0]?.className}," +
                            "{'formClassName', #args[0]?.formClassName}," +
                            "{'fieldType', #args[0]?.fieldType}," +
                            "{'isEnabled', #args[0]?.isEnabled}," +
                            "{'id', #args[1]}" +
                            "}"))
    public List<FormFieldGroup> listOfCache(FormFieldGroupDTO modelDTO, List<Long> ids) {
        //查询
        FormFieldGroup queryModel = new FormFieldGroup();
        if (modelDTO != null) {
            BeanUtils.copyProperties(modelDTO, queryModel);
        }
        QueryWrap<FormFieldGroup> wrapper = Wraps.q(queryModel);
        if (ids != null && !ids.isEmpty()) {
            wrapper.lambda().in(FormFieldGroup::getId, ids);
        }
        //添加其他业务查询条件
        wrapper.lambda().eq(FormFieldGroup::getIsDeleted, BusinessConstant.DELETE_NO);
        List<FormFieldGroup> modelList = list(wrapper);
        return modelList;
    }

    @Override
    public FormFieldGroupVO findById(Long id) {
        FormFieldGroup formFieldGroup = getByIdCache(id);
        if (formFieldGroup == null) {
            return null;
        }
//        List<String> fieldNameList = new ArrayList<>();
//        String dtoClassName = formFieldGroup.getDtoClassName();
//        try {
//            List list = ClassObjectUtil.getFiledsInfo("", new ArrayList(), Class.forName(dtoClassName).newInstance());
//            if (list != null && !list.isEmpty()) {
//                for (Object object : list) {
//                    Map map = (Map) object;
//                    fieldNameList.add(map.get("name").toString());
//                }
//            }
//        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
//            e.printStackTrace();
//        }
        FormFieldGroupVO formFieldGroupVO = doToVo(formFieldGroup);
//        formFieldGroupVO.setFieldNameList(fieldNameList);
        return formFieldGroupVO;
    }

    @Override
    public List<FormFieldGroupVO> queryList(FormFieldGroup formFieldGroup) {
        return null;
    }


    /**
     * do转vo
     *
     * @param model model
     * @return modelVo
     */
    @Override
    public FormFieldGroupVO doToVo(FormFieldGroup model) {
        FormFieldGroupVO modelVo = new FormFieldGroupVO();
        BeanUtils.copyProperties(model, modelVo);
        modelVo.setId(model.getId());
        return modelVo;
    }

    /**
     * do转vo
     *
     * @param modelList modelList
     * @return list
     */
    @Override
    public List<FormFieldGroupVO> doToVos(List<FormFieldGroup> modelList) {
        if (modelList == null || modelList.isEmpty()) {
            return null;
        }
        List<FormFieldGroupVO> result = new ArrayList<>();
        for (FormFieldGroup model : modelList) {
            result.add(doToVo(model));
        }
        return result;
    }

    @Override
    public CacheKeyBuilder getCacheKeyBuilder() {
        return new FormFieldGroupCacheKeyBuilder();
    }


    /**
     * 复制表单
     *
     * @param formFieldSubsystemDTO
     * @return 是否成功
     */
    @Override
    public R<Boolean> copyFormFieldList(FormFieldSubsystemDTO formFieldSubsystemDTO) {
        FormFieldDTO queryFormFieldDTO = new FormFieldDTO();
        queryFormFieldDTO.setGroupId(formFieldSubsystemDTO.getGroupId());
        List<FormField> formFieldList = formFieldService.list(queryFormFieldDTO, null);
        if (formFieldList != null && !formFieldList.isEmpty()) {
            for (FormField formField : formFieldList) {
                FormFieldSubsystem formFieldSubsystem = new FormFieldSubsystem();
                BeanUtils.copyProperties(formField, formFieldSubsystem, "id");
                formFieldSubsystem.setRelatedId(formFieldSubsystemDTO.getRelatedId());
                if (formField.getFieldTypeAttribute() != null) {
                    formFieldSubsystem.setFieldTypeAttribute(FormFieldSubsystemFieldTypeAttributeEnum.get(formField.getFieldTypeAttribute().getCode()));
                }
                if (formField.getMethodType() != null) {
                    formFieldSubsystem.setMethodType(FormFieldSubsystemMethodTypeEnum.get(formField.getMethodType().getCode()));
                }
                formFieldSubsystemService.save(formFieldSubsystem);
            }
        }
        return R.success(Boolean.TRUE);
    }

    /**
     * 同步业务表单
     *
     * @param formFieldSubsystemDTO 表单
     * @return
     */
    @Override
    public R sycnsubmitForm(@RequestBody FormFieldSubsystemDTO formFieldSubsystemDTO) {
        FormFieldSubsystemDTO queryFormFieldSubsystemDTO = new FormFieldSubsystemDTO();
        queryFormFieldSubsystemDTO.setRelatedId(formFieldSubsystemDTO.getRelatedId());
        List<FormFieldSubsystem> formFieldSubsystemList = formFieldSubsystemService.list(queryFormFieldSubsystemDTO, null);
        if (formFieldSubsystemList == null || formFieldSubsystemList.isEmpty()) {
            return R.success();
        }
        FormFieldDTO formFieldDTO = new FormFieldDTO();
        formFieldDTO.setGroupId(formFieldSubsystemList.get(0).getGroupId());
        List<FormField> formFieldList = formFieldService.list(formFieldDTO, null);
        if (formFieldList == null || formFieldList.isEmpty()) {
            return R.success();
        }
        for (FormField formField1 : formFieldList) {
            boolean pan = true;
            for (FormFieldSubsystem formFieldSubsystem : formFieldSubsystemList) {
                if (formField1.getKeyword().equals(formFieldSubsystem.getKeyword())) {
                    pan = false;
                }
            }
            if (pan) {
                FormFieldSubsystem saveFormFieldSubsystem = new FormFieldSubsystem();
                BeanUtils.copyProperties(formField1, saveFormFieldSubsystem, "id");
                if (formField1.getFieldTypeAttribute() != null) {
                    saveFormFieldSubsystem.setFieldTypeAttribute(FormFieldSubsystemFieldTypeAttributeEnum.get(formField1.getFieldTypeAttribute().getCode()));
                }
                if (formField1.getMethodType() != null) {
                    saveFormFieldSubsystem.setMethodType(FormFieldSubsystemMethodTypeEnum.get(formField1.getMethodType().getCode()));

                }
                saveFormFieldSubsystem.setRelatedId(formFieldSubsystemDTO.getRelatedId());
                formFieldSubsystemService.save(saveFormFieldSubsystem);
            }
        }
        return R.success();
    }
}
